package com.example.comiccenter.service.implt;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.comiccenter.dao.ChapterMapper;
import com.example.comiccenter.dao.ComicMapper;
import com.example.comiccenter.dao.PageMapper;
import com.example.comiccenter.domain.Chapter;
import com.example.comiccenter.domain.Comic;
import com.example.comiccenter.domain.ComicPage;
import com.example.comiccenter.utils.ResultData;
import com.example.comiccenter.utils.SearchBean;
import com.example.comiccenter.service.ComicService;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.example.comiccenter.utils.Consts.rootPath;
import static com.example.comiccenter.utils.Consts.targetRootPath;

@Service
public class ComicServiceImpl implements ComicService {
    @Resource
    private ChapterMapper chapterMapper;
    @Resource
    private ComicMapper comicMapper;
    @Resource
    private PageMapper pageMapper;



    public ResultData getAllComic(SearchBean<Comic> searchBean) {
        QueryWrapper<Comic> wrapper = new QueryWrapper<>();
        wrapper
                .eq(StrUtil.isNotBlank(searchBean.getData().getType()),"type",searchBean.getData().getType())
                .like(StrUtil.isNotBlank(searchBean.getData().getAuthor()),"author",searchBean.getData().getAuthor())
                .like(StrUtil.isNotBlank(searchBean.getData().getArea()),"area",searchBean.getData().getArea())
                .like(StrUtil.isNotBlank(searchBean.getData().getIsEnd()),"isEnd",searchBean.getData().getIsEnd())
                .like(StrUtil.isNotBlank(searchBean.getData().getName()),"name",searchBean.getData().getName())
                .like(StrUtil.isNotBlank(searchBean.getData().getUpdate_time()),"update_time",searchBean.getData().getUpdate_time())
                .orderBy(StrUtil.isNotBlank(searchBean.getOrderField()),searchBean.isAsc(),searchBean.getOrderField());
        Page<Comic> comicPage = comicMapper.selectPage(new Page<>(searchBean.getPageNum(), searchBean.getPageSize()), wrapper);
//        List<Comic> records = comicPage.getRecords();
//        records.forEach(System.out::println);

        return ResultData.success("查询成功",comicPage);
    }

    @Override
    public ResultData addComic(Comic comic, MultipartFile coverFile) {
        //查询该漫画是否已经存在
        String name = comic.getName();
        HashMap<String, Object> map = new HashMap<>();
        map.put("name",name);
        List<Comic> comics = comicMapper.selectByMap(map);
        System.out.println("该漫画存在的数量："+comics.size());
        if (comics.size()>0){
            return ResultData.error(400,"该漫画已存在，请修改名字");
        }

        //初始化信息
        comic.setFirst_upload(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        comic.setPageinner(comic.getName());
        comic.setUpdate_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        comic.setCollects(0);
        comic.setPages(0);
        comic.setScore((float)0);
        comic.setIsEnd("0");
        comic.setHeat(0);
        comic.setLikes(0);
        if (comic.getArea() == null || "".equals(comic.getArea())){
            comic.setArea("国产漫画");
        }
        //获取封面地址，并存入封面
        String fileName = comic.getName() + ".jpg";
        String coverStorage = "\\images\\cover\\" + fileName;
        String path = rootPath + "\\cover\\";
        String targetPath = targetRootPath + "\\cover\\";
        String coverPath = path + fileName;
        String targetCoverPath = targetPath + fileName;
        File file1 = new File(coverPath);
        File file2 = new File(targetCoverPath);
        try {
//            coverFile.transferTo(file1);
            FileUtils.copyInputStreamToFile(coverFile.getInputStream(), file1);
            FileUtils.copyInputStreamToFile(coverFile.getInputStream(), file2);
//            System.out.println(file1.getPath());

//            coverFile.transferTo(file2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        comic.setCover(coverStorage);
        //插入数据库
        int insert = comicMapper.insert(comic);
        //创建文件夹存储漫画
        String comicPath = comic.getName();
        String comicDirPath = rootPath + "\\comic\\";
        String targetcomicDirPath = targetRootPath + "\\comic\\";
        File file = new File(comicDirPath+comicPath);
        File file3 = new File(targetcomicDirPath+comicPath);
        file.mkdir();
        file3.mkdir();
        return ResultData.success("新建成功");
    }

    @Override
    public ResultData deleteComic(Comic comic) {
        comicMapper.deleteById(comic);

        //删除小说文件夹以及章节表中的记录和page
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        QueryWrapper<ComicPage> pageQueryWrapperrapper = new QueryWrapper<>();
        wrapper.eq("comicName",comic.getName());
        pageQueryWrapperrapper.eq("comicName",comic.getName());
        chapterMapper.delete(wrapper);
        pageMapper.delete(pageQueryWrapperrapper);
        //删除文件
        String comicFilePath = rootPath + "\\comic\\" + comic.getName() + "\\";
        String targetComicFilePath = targetRootPath + "\\comic\\" + comic.getName() + "\\";
        File comicFile = new File(comicFilePath);
        File targetComicFile = new File(targetComicFilePath);
        if (comicFile.exists()) {
            try {
                FileUtils.deleteDirectory(comicFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (targetComicFile.exists()){
            try {
                FileUtils.deleteDirectory(targetComicFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return ResultData.success("删除成功");
    }

    @Override
    public ResultData updateComic(Comic comic, MultipartFile coverFile) {
        if (coverFile != null){
            String originalFilename = coverFile.getOriginalFilename();
            String suffix = originalFilename.split("\\.")[1];
            if (!"jpg".equals(suffix)){
                return ResultData.error(401,"文件格式错误,请上传jpg文件");
            }else {
                //获取漫画名用于给封面命名
                QueryWrapper<Comic> wrapper = new QueryWrapper<>();
                wrapper.eq("id",comic.getId());
                String name = comicMapper.selectOne(wrapper).getName();

                String path = rootPath + "\\cover\\";
                String targetPath = targetRootPath + "\\cover\\";
                String fileName = name + ".jpg";
                String coverPath = path + fileName;
                String targetCoverPath = targetPath + fileName;

                String coverStorage = "\\images\\cover\\" + fileName;
                File file = new File(coverPath);
                File file1 = new File(targetCoverPath);
                try {
                    FileUtils.copyInputStreamToFile(coverFile.getInputStream(), file);
                    FileUtils.copyInputStreamToFile(coverFile.getInputStream(), file1);
//                    coverFile.transferTo(file);
//                    coverFile.transferTo(file1);
                    comic.setCover(coverStorage);
                    comicMapper.updateById(comic);
                    return ResultData.success("修改成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        comicMapper.updateById(comic);
        return ResultData.success("修改成功");
    }

    @Override
    public ResultData getMain() {
        ArrayList<String> types = new ArrayList<>();
        types.add("热门推荐");
        types.add("魔幻");
        types.add("科幻");
        types.add("热血");
        types.add("都市");
        types.add("灵异");
        types.add("武侠");
        types.add("现代");
        types.add("古风");
        HashMap<String, List<Comic>> comicMap = new HashMap<>();
        for (String type : types) {
            QueryWrapper<Comic> wrapper = new QueryWrapper<>();
            if ("热门推荐".equals(type)){
                wrapper.orderBy(true,false,"collects");
            }else{
                wrapper.eq("type",type);
            }
            List<Comic> records = comicMapper.selectPage(new Page<>(1, 5), wrapper).getRecords();
            comicMap.put(type,records);
        }
        return ResultData.success("查询成功",comicMap);
    }
}
